package com.iphanta.community.websocket;

import com.iphanta.community.user.traffic.UserNotificationReadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 4/7/22 11:48 AM
 */
@ServerEndpoint(value = "/user/ws/notification")
//@Component
public class NotificationWebSocket {

    private final static Map<String, Session> CLIENT_SESSION = new ConcurrentHashMap<>();
    private final static Map<String, String> SESSION_ID = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        Map<String, String> requestParams = getPathParameters(session);
        String uid = requestParams.get("uid");
        String token = requestParams.get("token");
        SESSION_ID.put(uid, session.getId());
        CLIENT_SESSION.put(session.getId(), session);
    }

    @OnClose
    public void onClose(Session session) {
        Map<String, String> requestParams = getPathParameters(session);
        String uid = requestParams.get("uid");
        String sessionId = SESSION_ID.remove(uid);
        CLIENT_SESSION.remove(sessionId);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        String UID = SESSION_ID.get(session);
        if(Objects.isNull(UID)) {
            return;
        }
        CLIENT_SESSION.get(UID).getAsyncRemote().sendObject(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }


    private Map<String, String> getPathParameters(Session session) {
        Map<String, String> requestParams = session.getPathParameters();
        return requestParams;
    }

}
